﻿using System.Data;
using WinFormsApp1.Common;
using System.Data.SqlClient;
using Newtonsoft.Json;
using static WinFormsApp1.Leo.week02.SplitRequisShow;

namespace WinFormsApp1.Leo.ListWeeks03
{
    public partial class SaleDisliteShow : Form
    {
        public SaleDisliteShow()
        {
            InitializeComponent();
            Struer();
        }

        //状态
        public void Struer()
        {
            uiComboBox1.Items.Add("正在运行");
            uiComboBox1.Items.Add("已停运");

            
        }
        
        public class SaleDisliteser
        {
            public int pageIndex { get; set; }

            public int pageSize { get; set; }

            public string SalesDetailsDate { get; set; }

            public string CustomerNickname { get; set; }

            public string SalesDetailsState { get; set; }
        };


        public int pageIndex = 1;

        public int pageSize = 8;

        public int totalcount = 0;

        public int pagecount = 0;

        public string SalesDetailsDate = "";

        public string CustomerNickname = "";

        public string SalesDetailsState = "";


        private async void SaleDisliteShow_Load(object sender, EventArgs e)
        {
            var clients = new SaleDisliteser
            {
                pageIndex = pageIndex,
                pageSize = pageSize,
                SalesDetailsDate= SalesDetailsDate,
                CustomerNickname= CustomerNickname,
                SalesDetailsState=SalesDetailsState
            };

            var items = await HttpClientHelper.RequestUrl<object, ApiResultFY1<List<SaleDisliteres>>>(URLCommon.Url2, "/WeekListOne_Leo/GeSaleDetaishow", HttpClientHelper.MethodType.POST, clients);
            this.dataGridView1.DataSource = items.Data.list;
            totalcount = items.Data.totalcount;
            pagecount = items.Data.pagecount;

            label1.Text = "共" + totalcount + "条,每页" + pageSize + "条，当前第" + pageIndex + "页，共" + pagecount + "页";
        }

        public class SaleDisliteres
        {
            public int SalesDetailsId { get; set; }

            /// <summary>
            /// 发货日期
            /// </summary>
            public DateTime SalesDetailsDate { get; set; }

            /// <summary>
            /// 客户名称
            /// </summary>
            public string CustomerNickname { get; set; }

            /// <summary>
            /// 订货件数
            /// </summary>
            public string SalesDetailsOrderNumber { get; set; }

            /// <summary>
            /// 订货数量
            /// </summary>
            public string SalesDetailsOrderNum { get; set; }

            /// <summary>
            /// 订单状态
            /// </summary>
            public bool SalesDetailsState { get; set; }
        }

        //状态显示判断

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Columns["订单状态"].Index && e.Value != null)
            {
                if (e.Value.ToString() == "True")
                {
                    e.Value = "正在运行";
                    e.FormattingApplied = true;
                }
                else
                {
                    e.Value = "已停运";
                    e.FormattingApplied = false;
                }
            }
        }
        //首页
        private void uiButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex != 1)
            {
                pageIndex = 1;
            }
            SaleDisliteShow_Load(sender, e);
        }
        //上一页
        private void uiButton6_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
            }
            else
            {
                //弹框提示
                MessageBox.Show("已经第一页了");
            }
            SaleDisliteShow_Load(sender, e);
        }
        //下一页
        private void uiButton7_Click(object sender, EventArgs e)
        {
            if (pageIndex < pagecount)
            {
                pageIndex++;
            }
            else
            {
                //弹框提示
                MessageBox.Show("已经最后一页了");
            }
            SaleDisliteShow_Load(sender, e);
        }
        //尾页
        private void uiButton8_Click(object sender, EventArgs e)
        {
            if (pageIndex != pagecount)
            {
                pageIndex = pagecount;
            }
            SaleDisliteShow_Load(sender, e);
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.dataGridView1.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;//设置重绘单元格样式
                    sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    e.PaintBackground(e.CellBounds, false);//重绘边框

                    //设置写入字体大小
                    System.Drawing.Font myFont = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);
                    SizeF sizeMod = e.Graphics.MeasureString("报表", myFont);

                    float FDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width);
                    float FMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width);

                    //设置每个“按钮的边界”
                    RectangleF recDel = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * FDel, e.CellBounds.Height);
                    RectangleF recMod = new RectangleF(recDel.Right, e.CellBounds.Top, e.CellBounds.Width * FMod, e.CellBounds.Height);
                    e.Graphics.DrawString("删除", myFont, Brushes.Black, recDel, sf);
                    e.Graphics.DrawString("报表", myFont, Brushes.Black, recMod, sf);
                    e.Handled = true;

                }
            }
        }

        public record SalesDetailes(int SalesDetailsId);
        //操作
        private async void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;
                if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    Graphics g = this.dataGridView1.CreateGraphics();
                    System.Drawing.Font myFont = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    SizeF sizeDel = g.MeasureString("删除", myFont);
                    SizeF sizeMod = g.MeasureString("报表", myFont);
                    float FDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width);
                    float FMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width);

                    Rectangle rectTotal = new Rectangle(0, 0, this.dataGridView1.Columns[e.ColumnIndex].Width, this.dataGridView1.Rows[e.RowIndex].Height);
                    RectangleF rectDel = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * FDel, rectTotal.Height);
                    RectangleF rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * FMod, rectTotal.Height);

                    if (rectDel.Contains(curPosition))
                    {
                        if (dataGridView1.Columns[e.ColumnIndex].Name == "Clas" && e.RowIndex >= 0)
                        {
                            if (MessageBox.Show("您确定要删除吗？", "此删除为逻辑删除", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                            {
                                int SalesDetailsId = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["序列"].Value);

                                SalesDetailes salesDetailes = new(SalesDetailsId);

                                var items = await HttpClientHelper.RequestUrl<SalesDetailes, ApiResult<List<SalesDetailres>>>(URLCommon.Url1, "/WorkList01_leo/GetSaleDetaisDel", HttpClientHelper.MethodType.POST, salesDetailes);

                                if (items.Code == 1)
                                {
                                    MessageBox.Show("删除成功");
                                }
                                else
                                {
                                    MessageBox.Show("删除失败");
                                }
                            }

                        }

                    }
                    else
                    if (rectMod.Contains(curPosition))
                    {

                        if (e.RowIndex >= 0)
                        {
                            int SalesDetailsId = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["序列"].Value);

                            Sale sale = new(SalesDetailsId);
                            sale.Show();
                        }

                    }

                }
            }
        }

        public class SalesDetailres
        {
            public int SalesDetailsId { get; set; }
        }

        //导入
        private async void uiButton1_Click(object sender, EventArgs e)
        {
            //DataTable source = new DataTable();
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFile.FileName;
                DataTable excelDt = ExcelHelper.ReadFromExcel(filePath);
                //把Excel读取到DataTable里面 然后再把DataTable存入数据库W
                AddDataTableToDB(excelDt);
            }
        }

        //将数据导入到sqlserver
        public bool AddDataTableToDB(DataTable source)
        {
            SqlTransaction tran = null;//声明一个事务对象
            try
            {
                using (SqlConnection conn = new SqlConnection("server=10.223.4.24;uid=sa;pwd=123456;database=SlaughterItemSQLServerNew;"))
                {
                    conn.Open();//打开链接
                    using (tran = conn.BeginTransaction())
                    {
                        using (SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
                        {
                            copy.DestinationTableName = "[SalesDetails]";  //指定服务器上目标表的名称
                            copy.WriteToServer(source);  //执行把DataTable中的数据写入DB  注意DataTable表结构要与数据库表结构一样
                            tran.Commit();              //提交事务
                            MessageBox.Show("已导入");
                            return true;            //返回True 执行成功！

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (null != tran)
                    tran.Rollback();
                //LogHelper.Add(ex);
                return false;//返回False 执行失败！
            }
        }


        //导出
        private async void uiButton2_Click(object sender, EventArgs e)
        {
            DataTable data = new DataTable();
            DataColumn dc = new DataColumn("发货日期");
            DataColumn dc2 = new DataColumn("客户名称");
            DataColumn dc3 = new DataColumn("订货件数");
            DataColumn dc4 = new DataColumn("订货数量");
            DataColumn dc5 = new DataColumn("订单状态");
            data.Columns.Add(dc);
            data.Columns.Add(dc2);
            data.Columns.Add(dc3);
            data.Columns.Add(dc4);
            data.Columns.Add(dc5);


            var items = await HttpClientHelper.RequestUrl<string, ApiResult<List<SaleDisliteres>>>(URLCommon.Url2, "/WeekListOne_Leo/GeSaleDetaishow2", HttpClientHelper.MethodType.GET, default);
            this.dataGridView1.DataSource = items.Data;


            for (int i = 0; i < items.Data.Count; i++)
            {
                DataRow row1 = data.NewRow();
                row1["发货日期"] = items.Data[i].SalesDetailsDate;
                row1["客户名称"] = items.Data[i].CustomerNickname;
                row1["订货件数"] = items.Data[i].SalesDetailsOrderNumber;
                row1["订货数量"] = items.Data[i].SalesDetailsOrderNum;
                row1["订单状态"] = items.Data[i].SalesDetailsState;
                data.Rows.Add(row1);
            }


            FolderBrowserDialog folder = new FolderBrowserDialog();
            if (folder.ShowDialog() == DialogResult.OK)
            {
                string ExportDir = folder.SelectedPath + "\\数据导出" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
                int i = ExcelHelper.DataTableToExcel(data, "测试", ExportDir, true);
                MessageBox.Show("已导出".ToString());
            }
        }

        //添加
        private void uiButton3_Click(object sender, EventArgs e)
        {
            SaleDisliteAdd saleDisliteAdd = new SaleDisliteAdd();
            saleDisliteAdd.Show();
            this.Hide();
        }

        //查询
        private void uiButton4_Click(object sender, EventArgs e)
        {
            if (uiDatePicker1 != null)
            {
                SalesDetailsDate = Convert.ToString(uiDatePicker1.Text);
            }

            if (uiTextBox1 != null)
            {
                CustomerNickname = uiTextBox1.Text;
            }


            if (uiComboBox1.Text == "正在运行")
            {
                SalesDetailsState= Convert.ToString(uiComboBox1.SelectedValue = true);
            }

            if (uiComboBox1.Text == "已停运")
            {
                SalesDetailsState= Convert.ToString(uiComboBox1.SelectedValue = false);
            }

            SaleDisliteShow_Load(sender,e);
        }
    }
}

